using IdentityModel.Client;
using Microsoft.AspNetCore.Mvc;
using NUglify;
using System.Net.Http.Headers;
using System.Text.Json;
using Volo.Abp.AspNetCore.Mvc;

namespace Ebusiness_Logs.Controllers
{
    [ApiController]
    [Route("api/[controller]/[action]")]
    public class AccessTokenController : AbpController
    {
        private static readonly string[] Summaries = new[]
        {
            "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
        };

        private readonly ILogger<AccessTokenController> _logger;

        public AccessTokenController(ILogger<AccessTokenController> logger)
        {
            _logger = logger;
        }

        [HttpGet(Name = "GetWeatherForecast")]
        public IEnumerable<WeatherForecast> Get()
        {
            return Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
                TemperatureC = Random.Shared.Next(-20, 55),
                Summary = Summaries[Random.Shared.Next(Summaries.Length)]
            })
            .ToArray();
        }


        /// <summary>
        /// 获取身份认证鉴权
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<string> GetApplicationToken()
        {
            //const string email = "admin@abp.io";
            //const string password = "1q2w3E*";
            const string server = "https://localhost:5272";
            const string clientId = "Ebusiness_Logs";
            const string clientSecret = "1q2w3e*";

            var client = new HttpClient();

            //1、获取所有的接口
            var configuration = await client.GetDiscoveryDocumentAsync(server);
            if (configuration.IsError)
            {
                throw new Exception(configuration.Error);
            }

            client = new HttpClient();
            var reflustToken = await client.RequestRefreshTokenAsync(new RefreshTokenRequest()
            {
                ClientId = clientId,  //客户端id
                ClientSecret = clientSecret,  //客户端密码
                RefreshToken = "",
                Scope = "",
                Resource = { "" }
            });
            //2、准备客户端id和密码，微服务信息
            var tokenResponse = await client.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest
            {
                Address = configuration.TokenEndpoint, //生成token接口
                ClientId = clientId,  //客户端id
                ClientSecret = clientSecret,  //客户端密码
                Scope = "Seckills profile roles email phone offline_access", //微服务名称，（核心授权）
            });

            if (tokenResponse.IsError)
            {
                Console.WriteLine(tokenResponse.Error);
            }

            Console.WriteLine("Access token: {0}", tokenResponse.AccessToken);
            Console.WriteLine();
            Console.WriteLine("Refresh token: {0}", tokenResponse.RefreshToken);
            Console.WriteLine();


            //Console.WriteLine();

            //访问秒杀服务
            //const string serverApi = "https://localhost:44301/api/abp/application-configuration";
            const string api = "http://localhost:5128/WeatherForecast";
            var serverRequest = new HttpRequestMessage(HttpMethod.Get, api);
            serverRequest.Headers.Authorization = new AuthenticationHeaderValue("Bearer", tokenResponse.AccessToken);

            var serverResponse = await client.SendAsync(serverRequest);
            serverResponse.EnsureSuccessStatusCode();
            var datamsg = await serverResponse.Content.ReadAsStringAsync();

            //Console.WriteLine("ClientCredentials API response: {0}", JsonSerializer.Serialize(JsonDocument.Parse(await serverResponse.Content.ReadAsStringAsync()), new JsonSerializerOptions
            //{
            //    WriteIndented = true
            //}));

            return datamsg;
        }
    }
}
